<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { globalParametersFormSchema } from './GlobalParameters.data';
  import { useGlobalParametersStore } from '@/store/modules/globalParameters';
  import { GlobalParameters } from '#/store';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();

  const { error } = createMessage;

  defineOptions({ name: 'GlobalParametersModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: globalParametersFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增全局参数' : '编辑全局参数'));

  const emptyGlobalParametersList = ref<GlobalParameters[]>([]);
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      const globalParametersStore = useGlobalParametersStore();
      const globalParametersList = globalParametersStore.getGlobalParametersList;

      if (globalParametersList) {
        emptyGlobalParametersList.value = globalParametersList;
      }
      const globalParameters: GlobalParameters = {
        name: values.name,
        value: values.value,
        type: values.type,
      };
      let exist =
        emptyGlobalParametersList.value.filter((globalParameters) => {
          return globalParameters.name == values.name && globalParameters.type == values.type;
        }).length != 0;
      if (exist) {
        error(values.type + '参数：[' + values.name + ']已经存在');
        return;
      }
      console.log(emptyGlobalParametersList.value);

      globalParametersList.push(globalParameters);
      globalParametersStore.setGlobalParametersList(emptyGlobalParametersList.value);
      console.log(values);
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
